<?php
/**
 * AccountsController is for all accounts operation before signing in.
 * 
 * Bocheng Chen, 10.07.2012
 * 
 * LBB Solutions Oy 版权所有 @ 2012
 */
class AccountsController extends Controller
{
	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
		if (!Yii::app()->user->isGuest) {
			$this->redirect(Yii::app()->createUrl('/user'), true);
		}
		
		$model = new LoginForm('login');

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if (isset($_POST['LoginForm']))
		{
			$model->attributes = $_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if ($model->validate()) {
				$this->redirect(Yii::app()->request->urlReferrer, true);
			}
		}
		// display the login form
		if (Yii::app()->request->isAjaxRequest) {
			$this->renderPartial('_login', array('model'=>$model));
		} else $this->render('login', array('model'=>$model));
	}
	
	/**
	 * Displays the login page
	 */
	public function actionSignup()
	{
		if (!Yii::app()->user->isGuest) {
			$this->redirect(Yii::app()->createUrl('/user'), true);
		}
		
		//TODO: go to code page
		$this->redirect(Yii::app()->createUrl('/code'), true);
		
		$model = new LoginForm('signup');
		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='signup-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
		
		// collect user input data
		if (isset($_POST['LoginForm']))
		{
			$model->attributes = $_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if ($model->validate() && $model->signup()) {
				$returnUrl = empty(Yii::app()->user->returnUrl) ? Yii::app()->createUrl('/user') : Yii::app()->user->returnUrl;
				$this->redirect($returnUrl, true);
			}
		}
		
		// display the signup page
		if (Yii::app()->request->isAjaxRequest) {
			$this->renderPartial('signup', array('model'=>$model));
		} else {
			$this->render('signup', array('model'=>$model));
		}
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->request->urlReferrer);
	}

	/**
	 * For facebook auth login. 
	 */
	public function actionFacebook()
	{
		if (empty($_POST)) {
			Yii::log("ERROR : /accounts/facebook : No post paramter!", CLogger::LEVEL_ERROR);
			BUtils::sendJson(500, 'Login Failed! We will resolve it ASAP.');
		}

		//1. init facebook API SDK
		require_once(Yii::app()->basePath . '/extensions/fbapi/facebook.php');
		$facebook = new Facebook(array(
			'appId'  => Yii::app()->params['facebook']['appId'],
			'secret' => Yii::app()->params['facebook']['secret'],
			'cookie' => true, // enable optional cookie support
		));
		//2. get user profile info
		$userFbId = $facebook->getUser();
		$userFbProfile = null;
		if ($userFbId) {
			try {
				$userFbProfile = $facebook->api('/me');
			} catch (FacebookApiException $e) {
				Yii::log("ERROR : /accounts/facebook : Get exception of facebook.\n" . $e->getTraceAsString(), CLogger::LEVEL_ERROR);
				BUtils::sendJson(500, $e->getMessage());
			}
		}
		if ($userFbProfile) {
			// get picture
			$url_face_50 = "http://graph.facebook.com/{$userFbProfile['id']}/picture";
			
			//set login with facebook profile
			$params = array(
				'email' => $userFbProfile['email'],
				'site_id' => 1,
				'site_user_id' => $userFbProfile['id'],
			);
			//set language with facebook locate
			if (!empty($userFbProfile['locale'])) BUtils::SetLanguage($userFbProfile['locale']);
			
			//checking with DB
			$sql_select_user = 'SELECT id, site_user_id, mobile, email, name, password, picture, gender, location, lang, status FROM tbl_user_account 
				WHERE (site_id=:site_id AND site_user_id=:site_user_id) or email=:email';
			$connection = Yii::app()->db;
			$command = $connection->createCommand($sql_select_user);
			$rows = $command->queryAll(true, $params);
			if (count($rows) == 0) {
				//create user account
				$params_more = $params;
				$params_more['username'] = $userFbProfile['username'];
				$params_more['picture'] = $url_face_50;
				$params_more['name'] = $userFbProfile['name'];
				$params_more['gender'] = $userFbProfile['gender'];
				$params_more['location'] = isset($userFbProfile['location']['name']) ? $userFbProfile['location']['name']: '';
				$command = $connection->createCommand('INSERT INTO tbl_user_account (email, username, picture, site_id, site_user_id, name, gender, location)
					VALUES(:email, :username, :picture, :site_id, :site_user_id, :name, :gender, :location)');
				$command->execute($params_more);
				$command = $connection->createCommand($sql_select_user);
				$row = $command->queryRow(true, $params);
			} elseif (count($rows) == 1) {
				$row = $rows[0];
				//only update the picture url if no picture url
				if (empty($row['picture'])) {
					$command = $connection->createCommand('UPDATE tbl_user_account SET picture=:picture, last_login_time=NOW() WHERE id=:id');
					$command->execute(array(':picture'=> $url_face_50, ':id'=>$row['id']));
				}
			} else {
				$row = $rows[0];
				Yii::log("WARN: find multiplay user accounts with Facebook login.\n"
					. print_r($rows, 1), CLogger::LEVEL_WARNING);
				BUtils::sendMaiToAdmin("WARN: find multi-users with Facebook login", print_r($rows, 1), 'admin@yamii.fi');
			}
			$connection->active = false;
			
			//login
			if (!empty($row['id'])) {
				$email = empty($row['email']) ? $row['id'] : $row['email'];
				$identity = new UserIdentity($email, $row['password']);
				$identity->setId($row['id']);
				$identity->setState('email', $row['email']);
				$identity->setState('mobile', $row['mobile']);
				$identity->setState('status', $row['status']);
				$identity->setState('name', $row['name']);
				$identity->setState('gender', $row['gender']);
				$identity->setState('picture', $row['picture']);
				$identity->setState('location', $row['location']);
				$identity->setState('lang', $row['lang']);
				$identity->setState('time_zone', $row['time_zone']);
				$identity->setState('facebook', 1);
				Yii::app()->user->login($identity, 0);
			}
		}
		BUtils::sendJson(200, 'Login done!');
	}
	
	/**
	 * Connect facebook when login
	 * @throws CHttpException
	 */
	public function actionConnectFacebook()
	{
		if (!Yii::app()->request->isAjaxRequest) {
			throw new CHttpException(404, 'The requested page is only for AJAX request.');
		}
		
		//1. init facebook API SDK
		require_once(Yii::app()->basePath . '/extensions/fbapi/facebook.php');
		$facebook = new Facebook(array(
			'appId'  => Yii::app()->params['facebook']['appId'],
			'secret' => Yii::app()->params['facebook']['secret'],
			'cookie' => true, // enable optional cookie support
		));
		//2. get user profile info
		$userFbId = $facebook->getUser();
		$userFbProfile = null;
		if ($userFbId) {
			try {
				$userFbProfile = $facebook->api('/me');
			} catch (FacebookApiException $e) {
				Yii::log("ERROR : /account/connectFacebook : Get exception of facebook.\n" . $e->getTraceAsString(), CLogger::LEVEL_ERROR);
				BUtils::sendJson(500, $e->getMessage());
			}
		} else {
			Yii::log("ERROR : /account/connectFacebook : Cannot get facebook user id.", CLogger::LEVEL_ERROR);
			BUtils::sendJson(500, Yii::t('Facebook login failed!'));
		}
		if ($userFbProfile) {
			Yii::app()->user->setState('fb_user', $userFbProfile);
			BUtils::sendJson(200, $userFbProfile);
		} else {
			Yii::log("ERROR : /account/connectFacebook : Cannot get facebook user information : {$userFbId}.", CLogger::LEVEL_ERROR);
			BUtils::sendJson(500, Yii::t('Facebook login failed!'));
		}
	}
	
	/**
	 * Language options
	 */
	public function actionLanguage() {
		$ref = Yii::app()->request->getUrlReferrer();
		if (empty($ref)) $url = Yii::app()->homeUrl;
		else $url = $ref;
		
		BUtils::SetLanguage($_GET['lang']);
		$this->redirect($url);
	}
	
	/**
	 * Push client message
	 */
	public function actionPush() {
		BUtils::Logging('push', $_REQUEST);
	}
	
	/**
	 * Push client message
	 */
	public function actionDebug() {
		echo '<pre>';
		print_r($_SESSION);
		print_r($_COOKIE);
		echo '</pre>';
	}
}